package com.example.mybaseapp.ui.localbroadcastreceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.mybaseapp.R

class LocalBroadcastReceiverActivity : AppCompatActivity() {
    private lateinit var localBroadcastManager:LocalBroadcastManager
    private lateinit var localReceiver: MyLocalBroadcastReceiver
    private lateinit var allReceiver: MyBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_local_broadcast_receiver)
        initView()
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initView() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this)
        localReceiver = MyLocalBroadcastReceiver()
        localBroadcastManager.registerReceiver(localReceiver, IntentFilter("com.example.mybaseapp.ui.localbroadcastreceiver"))
        allReceiver = MyBroadcastReceiver()
        registerReceiver(allReceiver, IntentFilter("com.example.mybaseapp.ui.localbroadcastreceiver"))
        findViewById<Button>(R.id.btn_local).apply {
            setOnClickListener {
                localBroadcastManager.sendBroadcast(Intent("com.example.mybaseapp.ui.localbroadcastreceiver"))
            }
        }
        findViewById<Button>(R.id.btn_unregister).apply {
            setOnClickListener {
                localBroadcastManager.unregisterReceiver(localReceiver)
                unregisterReceiver(allReceiver)
            }
        }
        findViewById<Button>(R.id.btn_broadcast).apply {
            setOnClickListener {
                sendBroadcast(Intent("com.example.mybaseapp.ui.localbroadcastreceiver"))
            }
        }
    }
}

class MyLocalBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // 处理接收到的本地广播
        Toast.makeText(context, "本地广播", Toast.LENGTH_SHORT).show()
    }
}

class MyBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        // 处理接收到的广播
        Toast.makeText(context, "全局广播", Toast.LENGTH_SHORT).show()
    }
}